package com.xiaowu.commons.scan;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;

/**
 * 异常处理，对ajax类型的异常返回ajax错误，避免页面问题
 * Created by chunmeng.lu
 * Date: 2016-24-03 16:18
 */
@Component
public class ExceptionResolver implements HandlerExceptionResolver {

	public ModelAndView resolveException(HttpServletRequest request,
										 HttpServletResponse response, Object handler, Exception e) {
		System.out.println("异常。。。");
		System.out.println(e);
		System.out.println(e.getMessage());
		
		System.out.println(request.getRequestURL());
		System.out.println(request.getRequestURI());
		

		HandlerMethod handlerMethod = (HandlerMethod) handler;
		if(null != handlerMethod){
			// spring ajax 返回含有 ResponseBody 或者 RestController注解
			ResponseBody annotation = handlerMethod.getMethodAnnotation(ResponseBody.class);
			RestController restAnnotation = handlerMethod.getBean().getClass().getAnnotation(RestController.class);
			if (null != annotation || null != restAnnotation) {
				Result result = new Result(200, e.getMessage());
				//return null;
				
				//返回异常提示
				ModelAndView mv = new ModelAndView();  
		        /*  使用FastJson提供的FastJsonJsonView视图返回，不需要捕获异常   */  
		         FastJsonJsonView view = new FastJsonJsonView();  
		         Map<String, Object> attributes = new HashMap<String, Object>();  
		         attributes.put("code", "1000001");  
		         attributes.put("msg", e.getMessage());  
		         view.setAttributesMap(attributes);  
		         mv.setView(view);   
		         return mv;  
			}
		}
		
		ModelAndView model = new ModelAndView("error/500");
		model.addObject("error",e.getMessage());
		return model;
	}

}